package com.demo.doc_pdf_demo.util;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.File;

/**
 * @Description: 使用 jacob-1.17 + windows + office 转换pdf
 * @Author: L.Wen
 * @Date: 2021/6/24 15:35
 */
public class Word2PdfUtil {

    /**
     * PDF 格式
     */
    static final int WD_FORMAT_PDF = 17;

    public static void wordToPDF(String sfileName, String toFileName) {

        System.out.println("启动Word...");
        final String property = System.getProperty("java.library.path");
        System.out.println(property);
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();
            doc = Dispatch.call(docs, "Open", sfileName).toDispatch();
            System.out.println("打开文档..." + sfileName);
            System.out.println("转换文档到PDF..." + toFileName);
            File tofile = new File(toFileName);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc,
                    "SaveAs",
                    toFileName,
                    WD_FORMAT_PDF);
            long end = System.currentTimeMillis();
            // 清除临时文件
            File sfile = new File(sfileName);
            if (sfile.exists()) {
                sfile.delete();
            }
            System.out.println("转换完成..用时：" + (end - start) + "ms.");

        } catch (Exception e) {
            System.out.println("========Error:文档转换失败：" + e.getMessage());
        } finally {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null) {
                app.invoke("Quit", new Variant[]{});
            }
        }
        // 如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
    }

    public static void main(String[] args) {
        wordToPDF("D:\\tmpfile\\work\\223456.docx", "D:\\tmpfile\\work\\223456-.pdf");
    }


}
